package com.lyf.controll;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.json.JSONObject;
import com.lyf.result.Code;
import com.lyf.result.Result;
import com.lyf.utils.CrossRegion;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/getCode/*")
public class CheckCodeControll extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决跨域
        CrossRegion.setCross(resp);
        //生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 50, 4, 50);
        //得到验证码
        String checkCode = lineCaptcha.getCode();
        System.out.println("生成的验证码："+checkCode);
        JSONObject jo = new JSONObject();
//        HttpSession session = req.getSession();
//        session.setAttribute("checkCode",checkCode);
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.auth("123456");
        jedis.set("checkCode",checkCode);
        //返回Base64编码的图片JSON字符串
//        String imageBase64Data = lineCaptcha.getImageBase64Data();
//
        Map<String,Object> map = new HashMap<>();

        //返回字符验证码

        Result result = new Result(Code.OK,checkCode,"验证码发送成功");

        map.put("result",result);
        jo.putAll(map);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println(jo.toString());//响应到浏览器

    }
}
